package coba.mailing.mail;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;

import coba.mailing.body.Body3;
import coba.mailing.function.NextXday;
import coba.mailing.jdbc.ConnectionFactory;
import coba.mailing.model.Atractivo;
import coba.mailing.model.AtractivoSolicitud;
import coba.mailing.procedure.AddAllCC;
import coba.mailing.properties.MainProperties;
import coba.mailing.query.FindAllAtractivo;
import coba.mailing.query.FindAtractivoSolicitudConfirmadaByAtractivoIdWhereFechaItinerarioBetween;

public class Mail3 {

	public static void sendAll() throws ClassNotFoundException, IOException, SQLException, EmailException {
		Connection con = ConnectionFactory.getConnection();

		Calendar today0Hour = GregorianCalendar.getInstance();

		today0Hour.set(Calendar.HOUR_OF_DAY, 0);
		today0Hour.set(Calendar.MINUTE, 0);
		today0Hour.set(Calendar.SECOND, 0);
		today0Hour.set(Calendar.MILLISECOND, 0);

		Date mondayNextWeek = NextXday.nextXday(Calendar.MONDAY, today0Hour.getTime());
		Date saturdayNextWeek = NextXday.nextXday(Calendar.SATURDAY, mondayNextWeek);

		List<Atractivo> listAtractivo = FindAllAtractivo.find(con);

		for (Atractivo atractivo : listAtractivo) {

			if (atractivo.getMails() == null || atractivo.getMails().trim().equals(""))
				continue;

			List<AtractivoSolicitud> listAtractivoSolicitud = FindAtractivoSolicitudConfirmadaByAtractivoIdWhereFechaItinerarioBetween.
					find(con, atractivo.getRecorridoId(), mondayNextWeek, saturdayNextWeek);

			List<AtractivoSolicitud> listAtractivoSolicitudUniq = new LinkedList<AtractivoSolicitud>();
			Map<Long, Long> mapHora = new HashMap<Long, Long>();
			Set<Long> mapSolicitudId = new HashSet<Long>();

			for (AtractivoSolicitud atractivoSolicitud : listAtractivoSolicitud) {
				if (!mapSolicitudId.contains(atractivoSolicitud.getSolicitudId())) {
					listAtractivoSolicitudUniq.add(atractivoSolicitud);
					mapHora.put(atractivoSolicitud.getSolicitudId(), atractivoSolicitud.getHora());
					mapSolicitudId.add(atractivoSolicitud.getSolicitudId());
				}
				else {
					if (atractivoSolicitud.getHora() < mapHora.get(atractivoSolicitud.getSolicitudId()).longValue()) {
						mapHora.put(atractivoSolicitud.getSolicitudId(), atractivoSolicitud.getHora());
					}
				}
			}

			if (!listAtractivoSolicitudUniq.isEmpty())
				send(mondayNextWeek, saturdayNextWeek, atractivo, listAtractivoSolicitudUniq, mapHora);

		}

		con.close();
	}

	public static void send(Date monday, Date saturday, Atractivo atractivo, List<AtractivoSolicitud> listAtractivoSolicitud, Map<Long, Long> mapHora) throws EmailException, IOException {
		MainProperties mainProperties = MainProperties.getInstance();

		HtmlEmail email = new HtmlEmail();

		email.setCharset("utf-8");
		email.setHostName(mainProperties.getProperty("smtpServer"));
		email.setSmtpPort(Integer.valueOf(mainProperties.getProperty("smtpPort")));

		if (atractivo.getMails().contains(",")) {
			for (String mail : atractivo.getMails().split(",")) {
				email.addTo(mail.trim(), atractivo.getNombre());
			}
		}
		else
			email.addTo(atractivo.getMails().trim(), atractivo.getNombre());

		email.setFrom(mainProperties.getProperty("fromMail"), mainProperties.getProperty("fromName"));

		AddAllCC.addAllCC(email, mainProperties.getProperty("mail3Ccs"));

		email.setSubject(subject(monday, saturday));

		String cid = email.embed(ClassLoader.getSystemClassLoader().getResource("coba-mail-footer.jpg"), "Conociendo footer");

		email.setHtmlMsg(Body3.get(cid, listAtractivoSolicitud, mapHora));

		email.send();
	}

	private static String subject(Date monday, Date saturday) {

		String[] arrMes = { "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio",
				"Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre" };

		StringBuilder subject = new StringBuilder("ConociendoBA - Visitas Semana del ");
		
		Calendar calMonday = GregorianCalendar.getInstance();
		calMonday.setTime(monday);

		subject.append(calMonday.get(Calendar.DAY_OF_MONTH));

		subject.append(" al ");

		Calendar calSaturday = GregorianCalendar.getInstance();
		calSaturday.setTime(saturday);

		subject.append(calSaturday.get(Calendar.DAY_OF_MONTH));

		subject.append(" de ");

		subject.append(arrMes[calSaturday.get(Calendar.MONTH)]);

		return subject.toString();
	}

}
